package com.cyy.learn.asciiPicTool

import tornadofx.*
import com.cyy.util.TooltipUtil
import java.io.FileOutputStream
import org.apache.poi.ss.usermodel.FillPatternType
import org.apache.poi.xssf.usermodel.XSSFColor
import java.util.concurrent.CountDownLatch
import java.util.concurrent.SynchronousQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.ThreadPoolExecutor
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import com.cyy.util.FileChooserUtil
import com.cyy.util.ImageUtil
import net.coobird.thumbnailator.Thumbnails
import org.apache.commons.codec.binary.Base64
import org.apache.commons.io.FileUtils
import java.io.File
import java.text.SimpleDateFormat
import java.io.IOException
import java.util.*
import java.awt.*
import kotlin.math.roundToInt

class AsciiPicToolController: Controller() {
    fun filePathAction(){
        val file = FileChooserUtil.chooseFile()
        if (file != null) {
            filePathTextField.text = file.path
        }
    }

    fun buildBannerAction() {
        val path = filePath.value
        val base = "@#&$%*o!;."// 字符串由复杂到简单
        try {
            val stringBuffer = StringBuilder()
            var image = ImageUtil.getBufferedImage(path)
            if (imageSizeComboBox.value != "不压缩") {
                val size = imageSizeComboBox.value.split("*")
                image = Thumbnails.of(image).size(Integer.parseInt(size[0]), Integer.parseInt(size[1])).asBufferedImage()
            }
            var y = 0
            while (y < image!!.height) {
                for (x in 0 until image!!.width) {
                    val pixel = image!!.getRGB(x, y)
                    val r = pixel and 0xff0000 shr 16
                    val g = pixel and 0xff00 shr 8
                    val b = pixel and 0xff
                    val gray = 0.299f * r + 0.578f * g + 0.114f * b
                    val index = (gray * (base.length + 1) / 255).roundToInt()
                    stringBuffer.append(if (index >= base.length) " " else base.get(index).toString())
                }
                stringBuffer.append("\n")
                y += 2
            }
            codeTextArea.value=stringBuffer.toString()
//            asciiPicToolController.getCodeTextArea().setText(stringBuffer.toString())
        } catch (e: Exception) {
            e.printStackTrace()
            TooltipUtil.showToast(e.message.toString())
        }

    }

    fun buildBase64Action() {
        val path = filePath.value
        try {
            val encodeBase64 = Base64.encodeBase64String(FileUtils.readFileToByteArray(File(path)))
//            asciiPicToolController.getCodeTextArea().setText(encodeBase64)
            codeTextArea.value=encodeBase64
        } catch (e: IOException) {
            e.printStackTrace()
            TooltipUtil.showToast(e.message.toString())
        }

    }

    //base64编码转图片
    fun buildBase64ToImage(base64: String) {
        if (Base64.isBase64(base64)) {
            try {
                val base64Byte = Base64.decodeBase64(base64)
                //              Image image = new Image(new ByteArrayInputStream(base64Byte));
                val image = ImageUtil.getFXImage(base64Byte)
                imageImageView.image=image
                imageImageView.fitWidth = image!!.width
                imageImageView.fitHeight = image!!.height
            } catch (e: Exception) {
                e.printStackTrace()
                TooltipUtil.showToast("图片转换失败：" + e.message)
            }
        }
    }

    fun saveImageAction() {
        try {
            val fileName = "x" + SimpleDateFormat("yyyyMMddHHmm").format(Date()) + ".jpg"
            //            File file = FileChooserUtil.chooseSaveFile(fileName, new FileChooser.ExtensionFilter("All Images", "*.*"),
            //                    new FileChooser.ExtensionFilter("JPG", "*.jpg"), new FileChooser.ExtensionFilter("PNG", "*.png"),
            //                    new FileChooser.ExtensionFilter("gif", "*.gif"), new FileChooser.ExtensionFilter("jpeg", "*.jpeg"),
            //                    new FileChooser.ExtensionFilter("bmp", "*.bmp"));
            val file = FileChooserUtil.chooseSaveImageFile(fileName)
            if (file != null) {
                val fileType = file.path.split("\\.")
                //                ImageIO.write(SwingFXUtils.fromFXImage(asciiPicToolController.getImageImageView().getImage(), null), fileType[fileType.length - 1],
                //                        file);
                ImageUtil.writeImage( imageImageView.image, file)
                TooltipUtil.showToast("保存图片成功,图片在：" + file.path)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            TooltipUtil.showToast(e.message.toString())
        }

    }


    /**
     * 转换图片为Excel表
     */
    @Throws(Exception::class)
    fun saveImageToExcelAction() {
        TooltipUtil.showToast("正在转换，请稍后......")
        val path = filePath.value
        val imagePath = File(path)
        val bi = ImageUtil.getBufferedImage(imagePath)
        val width = bi!!.getWidth()
        val height = bi!!.getHeight()

        // 读取占位的文件，设置列宽
        val excel = XSSFWorkbook()
        val sht = excel.createSheet()

        val executor = ThreadPoolExecutor(height, height * width, 60L, TimeUnit.SECONDS, SynchronousQueue())
        val latch = CountDownLatch(height * width)
        for (i in 0 until height) {
            sht.setColumnWidth(i, 500.toShort().toInt())
            val row = sht.createRow(i)
            row.height = 250.toShort()
            for (j in 0 until width) {
                executor.execute {
                    val style = excel.createCellStyle()
                    style.setFillForegroundColor(XSSFColor(Color(bi!!.getRGB(j, i))))
                    style.setFillPattern(FillPatternType.SOLID_FOREGROUND)
                    row.createCell(j).setCellStyle(style)
                    log.info("完成" + j + "列：" + i)
                    latch.countDown()
                }
            }
        }
        latch.await()
        val outFile = File(imagePath.parent, imagePath.name.split("\\.")[0] + ".xlsx")
        val out = FileOutputStream(outFile)
        excel.write(out)
        excel.close()
        out.close()
        log.info("转换完成，文件保存在：" + outFile.absolutePath)
        TooltipUtil.showToast("转换完成，文件保存在：" + outFile.absolutePath)
    }
}